package com.tencent;


/**
 * @className: com.tencent.SingleNodeRever
 * @description:
 * @author: tong.li
 * @createTime: 2023/2/22 19:58
 * @copyright: Tongcheng-Elong Holdings Limited
 */
public class SingleNodeRever {

    static class Node {
        private Node next;
        private Integer data;

        public Node(Integer data) {
            this.data = data;
        }
    }


    /**
     * 1-2-3-4
     * @param args
     */
    public static void main(String[] args) {
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        node1.next = node2;
        node2.next = node3;
        Node node5 = new Node(5);
        Node node6 = new Node(6);
        node4.next = node5;
        print(add(node1, node4));

    }

    /**
     * 1-2-3-4-5-6-1 1-2-3-4-5-6 - 1-2-3-4-5-6 - 1-2-3-4-5-6
     * @param head
     * @return
     */
    public static boolean isHuan(Node head) {
        Node slow = head;
        Node fast = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (slow.equals(fast)) {
                return true;
            }
        }
        return false;
    }



    /**
     *
     * @param head
     */
    public static void print(Node head) {
        while (head != null) {
            System.out.print(head.data + "->") ;
            head = head.next;
        }
        System.out.println("null");
    }

    /**
     * 1-2-3
     * 3-2-1
     * @param head
     */
    public static Node reverse(Node head) {
        Node pre = null;
        Node next = null;
        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }

    public static Node add(Node head1, Node head2) {
        int headLen1 = len(head1);
        int headLen2 = len(head2);
        Node L = headLen1 >= headLen2 ? head1 : head2;
        Node S = L == head1 ? head2 : head1;
        Node currL = L;
        Node currS = S;
        int carry = 0;
        Node last = currL;
        int sum = 0;
        while (currS != null) {
            sum = currS.data + currL.data + carry;
            currL.data = sum % 10;
            carry = sum / 10;
            last = currL;
            currL = currL.next;
            currS = currS.next;
        }
        while (currL != null) {
            sum = currL.data + carry;
            currL.data = sum % 10;
            carry = sum / 10;
            last = currL;
            currL = currL.next;
        }
        if (carry != 0) {
            last.next = new Node(1);
        }
        return L;
    }

    private static int len(Node head1) {
        int len = 0;
        while (head1 != null) {
            len++;
            head1 = head1.next;
        }
        return len;
    }

}
